<template>
  <div class="main">
    <!-- 查询区 -->
    <el-form :model="queryParams" :inline="true">
      <el-form-item label="商品编码">
        <el-input
          v-model="queryParams.productSn"
          placeholder="请输入商品编码"
          style="width: 130px"
        />
      </el-form-item>
      <el-form-item label="商品名称">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入商品名称"
          style="width: 130px"
        />
      </el-form-item>
      <el-form-item label="分类">
        <el-select
          v-model="queryParams.categoryId"
          placeholder="请选择分类"
          clearable
          style="width: 130px"
        >
          <el-option
            v-for="item in categoryOptions"
            :key="item.categoryId"
            :label="item.categoryName"
            :value="item.categoryId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="价格区间">
        <el-input
          v-model="queryParams.minPrice"
          placeholder="最低价"
          style="width: 100px"
        />
        <span style="margin: 0 5px">-</span>
        <el-input
          v-model="queryParams.maxPrice"
          placeholder="最高价"
          style="width: 100px"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作区 -->
    <el-row :gutter="10">
      <el-col :span="1.5">
        <el-button type="primary" @click="handleAdd">新增商品</el-button>
        <el-button type="primary" @click="handleDeleteBatch"
          >批量删除</el-button
        >
        <el-button type="primary" @click="printTable">直接打印</el-button>
      </el-col>
    </el-row>

    <!-- 表格区 -->
    <el-table
      v-loading="loading"
      :data="dataList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" prop="index" width="55" align="center" />
      <el-table-column label="商品编码" prop="productSn" />
      <el-table-column label="商品图片" prop="productUrl">
        <template #default="scope">
          <img
            v-if="scope.row.productUrl"
            :src="parseImageUrl(scope.row.productUrl)"
            alt="商品图片"
            style="max-width: 100px"
            @error="handleImageError(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="商品名称" prop="productName" />
      <el-table-column label="分类名称" prop="categoryName" />
      <el-table-column label="价格" prop="price" />
      <el-table-column label="库存" prop="stockQuantity" />
      <el-table-column label="销售量" prop="salesQuantity" />
      <el-table-column label="创建时间" prop="createTime" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button
            link
            type="primary"
            size="small"
            @click="handleUpdate(scope.row)"
            >编辑</el-button
          >
          <el-button
            link
            type="primary"
            size="small"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
          <el-button
            link
            type="primary"
            size="small"
            @click="handleView(scope.row)"
            >查看</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区 -->
    <Pagination
      v-model:current-page="queryParams.pageNum"
      v-model:page-size="queryParams.pageSize"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="open" :title="title">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品编码">
          <el-input
            v-model="form.productSn"
            disabled
            placeholder="商品编码后台生成"
          />
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input v-model="form.productName" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="类别id">
              <el-input
                v-model="form.categoryId"
                disabled
                placeholder="根据类别内容显示相应id"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类别" prop="categoryId">
              <el-cascader
                v-model="form.categoryIds"
                :options="categoryOptions"
                :show-all-levels="false"
                placeholder="请选择类别"
                :props="{
                  checkStrictly: true,
                  value: 'categoryId',
                  label: 'categoryName',
                  children: 'children'
                }"
                clearable
                @change="handleCategoryChange"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="描述">
          <el-input v-model="form.productDescription" type="textarea" />
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="form.price" />
        </el-form-item>
        <el-form-item label="库存">
          <el-input v-model="form.stockQuantity" />
        </el-form-item>
        <el-form-item label="销售量">
          <el-input v-model="form.salesQuantity" />
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
            ref="uploadRef"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
            drag
            class="custom-uploader"
          >
            <div class="upload-content">
              <i class="el-icon-upload" />
              <div class="upload-text">
                将图片拖到此处，或 <em>点击选择</em>
              </div>
            </div>
          </el-upload>
          <img
            v-if="form.productUrl"
            :src="form.productUrl"
            alt="商品图片"
            class="preview-image"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm(formRef)"
            >确 定</el-button
          >
          <el-button v-show="!form.productSn" @click="resetForm(formRef)"
            >重 置</el-button
          >
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-drawer v-model="drawer" title="产品信息" :with-header="false">
      <el-descriptions :title="productTitle" :column="2" border>
        <el-descriptions-item label="编码">{{
          product.productSn
        }}</el-descriptions-item>
        <el-descriptions-item label="名称">{{
          product.productName
        }}</el-descriptions-item>
        <el-descriptions-item label="价格">{{
          product.price
        }}</el-descriptions-item>
        <el-descriptions-item label="类别">{{
          product.categoryName
        }}</el-descriptions-item>
        <el-descriptions-item label="商品描述">{{
          product.productDescription
        }}</el-descriptions-item>
        <el-descriptions-item label="销售量">{{
          product.salesQuantity
        }}</el-descriptions-item>
        <el-descriptions-item label="库存量">{{
          product.stockQuantity
        }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{
          product.createTime
        }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{
          product.updateTime
        }}</el-descriptions-item>
      </el-descriptions>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, toRef } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  listProductByPage,
  getProductBySn,
  addProduct,
  updateProduct,
  deleteProduct,
  deleteProductBatch,
  getProductByPrice
} from "@/api/product";
import type { ProductDTO, ProductForm, QueryParams } from "@/api/product";
import { listAllCategory } from "@/api/category";
import type { CategoryDTO } from "@/api/category";
import Pagination from "@/views/pos/components/Pagination.vue";

// 初始化加载数据
onMounted(async () => {
  await getCategoryOptions();
  getList();
});

/** ------------------数据查询区——表单-------------------- */
// 表单实例
const queryRef = ref<FormInstance>();

// 类别下拉框
const categoryOptions = ref<CategoryDTO[]>([]);

// 修改为异步函数
async function getCategoryOptions() {
  const response = await listAllCategory();
  categoryOptions.value = response.data;
  console.log("获取到的分类数据：", categoryOptions.value);
  return categoryOptions.value;
}

// 查询
const query = reactive<QueryParams>({
  pageNum: 1,
  pageSize: 5,
  productSn: undefined,
  productName: undefined,
  categoryId: undefined,
  minPrice: undefined,
  maxPrice: undefined
});
const queryParams = toRef(query);

// 数据查询区--> 查询按钮
function handleQuery() {
  queryParams.value.pageNum = 1; // 重置分页
  const { minPrice, maxPrice } = queryParams.value;
  if (minPrice !== undefined && maxPrice !== undefined) {
    getProductByPrice(minPrice, maxPrice)
      .then(response => {
        dataList.value = response.data; // 假设返回的数据是数组
        total.value = dataList.value.length; // 假设总条数为返回数据的长度
      })
      .catch(error => {
        console.error("查询失败：", error);
        ElMessage.error("查询失败，请检查输入");
      });
  } else {
    getList();
  }
}

// 数据查询区--> 重置按钮
const resetQuery = () => {
  queryParams.value.productSn = "";
  queryParams.value.productName = "";
  queryParams.value.categoryId = undefined;
  queryParams.value.minPrice = undefined;
  queryParams.value.maxPrice = undefined;
  handleQuery();
};

/** ------------------数据展示区——表格-------------------- */
// 数据列表
const loading = ref<boolean>(false); // table数据加载遮罩
const total = ref<number>(0); // table数据总数
const tableData = reactive<ProductDTO[]>([]); // table数据
const dataList = toRef(tableData);

// 数据展示区--> 数据加载
function getList() {
  loading.value = true;
  listProductByPage(queryParams.value).then(response => {
    const products = response.data.list;
    products.forEach((product, index) => {
      product.index =
        index +
        1 +
        (queryParams.value.pageNum - 1) * queryParams.value.pageSize; // 计算序号
    });
    dataList.value = products;
    total.value = response.data.total;
    loading.value = false;
  });
}

/** ------------------数据展示区：数据选择-------------------- */
const sns = ref<string[]>([]); // 表单勾选的id
const single = ref<boolean>(false); // 勾选1个
const multiple = ref<boolean>(false); // 勾选多个

// 数据展示区--> 勾选数据
function handleSelectionChange(selection: ProductDTO[]) {
  if (!selection) return; // 添加空值检查
  sns.value = selection.map((item: ProductDTO) => item.productSn);
  single.value = selection.length === 1;
  multiple.value = selection.length > 1;
}

/** ------------------数据展示区：分页加载-------------------- */
const handleSizeChange = (val: number) => {
  queryParams.value.pageSize = val;
  getList();
};

const handleCurrentChange = (val: number) => {
  queryParams.value.pageNum = val;
  getList();
};

/** ------------------数据编辑区——对话框+表单-------------------- */
// 表单数据
const formRef = ref<FormInstance>();
const uploadRef = ref(null);

const formData = reactive<ProductForm>({
  productSn: undefined,
  productName: undefined,
  categoryId: undefined,
  categoryName: undefined,
  categoryIds: [], // 修改为数组，用于存储级联选择器的值
  productDescription: undefined,
  price: 0.0,
  salesQuantity: undefined,
  stockQuantity: undefined,
  productUrl: undefined
});
const form = toRef(formData);

const rules = reactive<FormRules<ProductForm>>({
  // 表单验证规则
  productName: [{ required: true, message: "名称不能为空", trigger: "blur" }],
  categoryId: [{ required: true, message: "类别不能为空", trigger: "blur" }],
  price: [
    {
      pattern: /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/,
      message: "价格格式不正确, 参考20.50",
      trigger: "blur"
    }
  ]
});

// 对话框数据
const title = ref(""); // 对话框标题
const open = ref(false); // 对话框打开
const uploadUrl = ref("http://localhost:8080/upload"); // 上传图片的接口地址

// 数据编辑区-->提交按钮
const submitForm = async (formEl: FormInstance) => {
  if (!formEl) return;
  await formEl.validate((valid: boolean, fields: any) => {
    if (valid) {
      if (
        uploadRef.value &&
        uploadRef.value.uploadFiles &&
        uploadRef.value.uploadFiles.length > 0
      ) {
        uploadRef.value.submit(); // 如果有图片上传，先提交图片
      } else {
        submitProductForm();
      }
    } else {
      console.log("表单验证未通过", fields);
    }
  });
};

// 提交商品表单
const submitProductForm = () => {
  if (form.value.productSn) {
    // 如果有 productSn，调用更新接口
    updateProduct(form.value).then(() => {
      ElMessage({ type: "success", message: "修改数据成功" });
      getList();
      open.value = false;
    });
  } else {
    // 没有 productSn，调用新增接口
    addProduct(form.value).then(response => {
      if (response.code === 200) {
        const code = response.msg.match(/编码：(P\d+)/)?.[1];
        ElMessage({
          type: "success",
          message: `新增数据成功，编码：${code}`
        });
        getList(); // 刷新列表
        open.value = false; // 关闭对话框
      } else {
        ElMessage.error(response.msg || "新增数据失败");
      }
    });
  }
};

// 上传图片成功回调函数
const handleUploadSuccess = (response: any, file: any, fileList: any) => {
  if (response.code === 200) {
    const msg = response.msg;
    const startIndex = msg.indexOf("文件地址：");
    if (startIndex !== -1) {
      const imageUrl = msg.slice(startIndex + "文件地址：".length);
      form.value.productUrl = imageUrl;
    } else {
      ElMessage.error("上传成功，但未获取到图片URL");
      console.error("返回的数据中未包含有效的图片URL：", response);
    }
  } else {
    ElMessage.error("上传失败：" + response.msg);
  }
};

const beforeUpload = (file: any) => {
  const isJPG = file.type === "image/jpeg";
  const isPNG = file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG && !isPNG) {
    ElMessage.error("上传图片只能是 JPG/PNG 格式!");
  }
  if (!isLt2M) {
    ElMessage.error("上传图片大小不能超过 2MB!");
  }
  return (isJPG || isPNG) && isLt2M;
};

// 数据编辑区-->重置按钮
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  if (uploadRef.value) {
    uploadRef.value.clearFiles();
  }
  form.value = {
    productSn: undefined,
    productName: undefined,
    categoryId: undefined,
    categoryName: undefined,
    categoryIds: [],
    productDescription: undefined,
    price: 0.0,
    salesQuantity: undefined,
    stockQuantity: undefined,
    productUrl: undefined
  };
};

// 数据编辑区-->取消按钮
function cancel() {
  initForm();
  open.value = false;
}

// 处理级联选择器值变化
const handleCategoryChange = (value: number[]) => {
  // 取级联选择器的最后一级作为categoryId
  form.value.categoryId = value[value.length - 1];
  // 更新categoryName
  const selectedCategory = categoryOptions.value.find(
    item => item.categoryId === form.value.categoryId
  );
  form.value.categoryName = selectedCategory?.categoryName;
};

// 清空或赋值表单数据
const initForm = () => {
  formRef.value?.resetFields();
  if (uploadRef.value) {
    uploadRef.value.clearFiles();
  }
  form.value = {
    productSn: undefined,
    productName: undefined,
    categoryId: undefined,
    categoryName: undefined,
    categoryIds: [],
    productDescription: undefined,
    price: 0.0,
    salesQuantity: undefined,
    stockQuantity: undefined,
    productUrl: undefined
  };
};

// 数据操作区--> 新增按钮
function handleAdd() {
  initForm();
  title.value = "新增数据";
  open.value = true;
}

// 数据操作区区--> 修改按钮
async function handleUpdate(row: ProductDTO) {
  initForm();
  // 确保row存在并且productSn存在
  if (!row || !row.productSn) {
    ElMessage.error("商品信息不完整，请刷新后重试");
    return;
  }
  const sn = row.productSn;
  try {
    const response = await getProductBySn(sn);
    const data = response.data;
    // 检查data是否存在并且结构正确
    if (!data || typeof data !== "object") {
      ElMessage.error("获取到的商品数据无效");
      return;
    }
    // 检查data是否包含必要的字段
    if (!data.categoryId) {
      ElMessage.error("商品分类信息缺失");
      return;
    }
    // 填充表单数据前，确保数据结构匹配
    form.value = {
      ...data,
      categoryIds: getCategoryPath(data.categoryId) // 获取完整的分类路径
    };
    title.value = "修改数据[" + sn + "]";
    open.value = true;
  } catch (error) {
    console.error("获取商品信息失败:", error);
    ElMessage.error("获取商品信息失败，请稍后重试");
  }
}

// 根据 categoryId 获取完整的级联路径
function getCategoryPath(categoryId: number): number[] {
  if (!categoryId) return [];
  const path: number[] = [];
  const findPath = (categories: CategoryDTO[], id: number) => {
    for (const category of categories) {
      if (category.categoryId === id) {
        path.push(category.categoryId);
        return true;
      }
      if (category.children && findPath(category.children, id)) {
        path.push(category.categoryId);
        return true;
      }
    }
    return false;
  };
  findPath(categoryOptions.value, categoryId);
  return path.reverse();
}

// 数据操作区--> 删除按钮
function handleDelete(row: ProductDTO) {
  const sn = row.productSn;
  ElMessageBox.confirm("是否删除编号为" + sn + "的数据?", "警告")
    .then(() => {
      return deleteProduct(sn);
    })
    .then(() => {
      getList();
      ElMessage({ type: "success", message: "删除成功" });
    })
    .catch(() => {});
}

// 数据操作区--> 批量删除按钮
function handleDeleteBatch() {
  const productSns = sns.value;
  if (productSns.length === 0) {
    ElMessage.warning("请选择要删除的商品");
    return;
  }
  ElMessageBox.confirm("是否批量删除编号为" + productSns + "的数据?", "警告")
    .then(() => {
      return deleteProductBatch(productSns);
    })
    .then(() => {
      getList();
      ElMessage.success("批量删除成功");
    })
    .catch(() => {});
}

// 数据操作区-->抽屉查看数据
const drawer = ref<boolean>(false);
const productTitle = ref<string>("");
const product = ref<ProductDTO>({
  productSn: "",
  productName: "",
  categoryId: 0,
  categoryName: "",
  productDescription: undefined,
  price: 0.0,
  salesQuantity: undefined,
  stockQuantity: undefined,
  productUrl: undefined,
  createTime: undefined,
  updateTime: undefined,
  id: 0
});

// 数据操作区--> 查看按钮
function handleView(row: ProductDTO) {
  const productSn = row.productSn;
  getProductBySn(productSn)
    .then(response => {
      if (response.code === 200) {
        const data = response.data;
        product.value = data;
        productTitle.value = `查看产品数据[${productSn}]`;
        drawer.value = true;
      } else {
        ElMessage.error("获取商品信息失败，请稍后重试");
      }
    })
    .catch(error => {
      console.error("获取商品信息失败:", error);
      ElMessage.error("获取商品信息失败，请稍后重试");
    });
}

// 加载图片
const handleImageError = (row: ProductDTO) => {
  // 可以设置默认图片路径
  row.productUrl = "/default-image.jpg";
  ElMessage.warning("图片加载失败，已显示默认图片");
};

// 解析图片路径
const parseImageUrl = (url: string) => {
  if (!url) return "";
  const startIndex = url.indexOf("文件地址：");
  if (startIndex !== -1) {
    return url.slice(startIndex + "文件地址：".length);
  }
  return url;
};

// 打印功能
// 打印功能
const printTable = () => {
  // 检查是否有选中的数据
  if (sns.value.length === 0) {
    ElMessage.warning("请选择要打印的商品");
    return;
  }

  // 创建打印窗口
  const printWindow = window.open("", "_blank");

  // 生成HTML内容
  let content = `<html><head><title>商品打印</title>`;
  content += `<style>
    table {
      width: 100%;
      border-collapse: collapse;
      font-family: Arial, sans-serif;
    }
    th, td {
      border: 1px solid #dddddd;
      padding: 8px;
      text-align: center;
    }
    th {
      background-color: #f2f2f2;
      font-weight: bold;
    }
    tr:nth-child(even) {
      background-color: #f9f9f9;
    }
  </style>`;
  content += `</head><body>`;
  content += `<h1 style="text-align: center; font-family: Arial, sans-serif;">商品信息</h1>`;
  content += `<table>`;

  // 添加表头
  content += `<tr>`;
  content += `<th>序号</th>`;
  content += `<th>商品编码</th>`;
  content += `<th>商品名称</th>`;
  content += `<th>分类</th>`;
  content += `<th>价格</th>`;
  content += `<th>库存</th>`;
  content += `<th>销售量</th>`;
  content += `<th>创建时间</th>`;
  content += `</tr>`;

  // 添加表数据
  const selectedData = dataList.value.filter(item =>
    sns.value.includes(item.productSn)
  );
  selectedData.forEach((item, index) => {
    content += `<tr>`;
    content += `<td>${index + 1}</td>`; // 序号
    content += `<td>${item.productSn}</td>`;
    content += `<td>${item.productName}</td>`;
    content += `<td>${item.categoryName}</td>`;
    content += `<td>${item.price}</td>`;
    content += `<td>${item.stockQuantity}</td>`;
    content += `<td>${item.salesQuantity}</td>`;
    content += `<td>${item.createTime}</td>`;
    content += `</tr>`;
  });

  content += `</table></body></html>`;

  // 写入打印窗口
  if (printWindow) {
    printWindow.document.open();
    printWindow.document.write(content);
    printWindow.document.close();

    // 调用打印
    printWindow.onload = () => {
      printWindow.print();
      printWindow.close();
    };
  } else {
    ElMessage.error("无法打开打印窗口，请检查浏览器设置");
  }
};
</script>

<style scoped>
.main {
  padding: 20px;
}

.custom-uploader .el-upload-dragger {
  width: 360px;
  height: 180px;
  padding: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
}

.custom-uploader .el-upload-dragger:hover {
  border-color: #409eff;
}

.upload-content {
  text-align: center;
}

.upload-text {
  margin-top: 10px;
  color: #666;
}

.upload-text em {
  color: #409eff;
  font-style: normal;
  cursor: pointer;
}

.preview-image {
  max-width: 200px;
  margin-top: 10px;
  border: 1px solid #eee;
  border-radius: 4px;
}
</style>
